package com.huaxindata.im.main.contactview;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.huaxindata.im.R;
import com.huaxindata.im.main.contactview.friend.ContactListActivity;
import com.huaxindata.im.main.contactview.friend.HxPersonalCenterActivity;
import com.huaxindata.im.main.contactview.group.SelectGroupMemberActivity;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.main.menu.SearchContactActivity;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactPerson;

import java.util.ArrayList;
import java.util.List;

import static android.view.View.OVER_SCROLL_NEVER;

/**
 * 首页-通讯录，分组展示好友，群，和最近联系的好友
 * 最近常用联系人只显示最近常聊天的好友，不包括群
 */
public class ContactFragment extends Fragment implements ContactManager.OnContactRefresh {

    Toolbar            mToolbar;
    ExpandableListView mExpandableListView;
    View               mAddFriendView;
    private ExpandableListContactAdapter mAdapter;
    private List<ContactPerson>          mRecentContactList;

    private PopupWindow mPopupWindow;//点击toolbar上的加号弹出菜单
    private Context     mContext;

    public ContactFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact, container, false);
        initView(view);
        initData();
        return view;
    }

    public void initView(View view) {
        initPopupWindowMenu();
        mToolbar = (Toolbar) view.findViewById(R.id.fragment_contact_toolbar);
        mAddFriendView = view.findViewById(R.id.fragment_contact_toolbar_add);
        mExpandableListView = (ExpandableListView) view.findViewById(R.id.fragment_contact_expand_list);
        mAdapter = new ExpandableListContactAdapter(mContext);
        mExpandableListView.setAdapter(mAdapter);
        mExpandableListView.setOverScrollMode(OVER_SCROLL_NEVER);
        mExpandableListView.setGroupIndicator(null);
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                if (mAdapter.getGroupCount() == groupPosition + 1) {
                    //如果是最后一个Position,则让分组列表展开
                    return false;
                } else {
                    //分组列表不展开，跳转到对应的通讯录列表
                    Intent intent = new Intent(getActivity(), ContactListActivity.class);
                    intent.putExtra("type", groupPosition);
                    getActivity().startActivity(intent);
                    return true;//返回true表示分组不展开
                }
            }
        });
        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Contact contact = mRecentContactList.get(childPosition);
               /* ContactInfoDialog concatInfoWindow = new ContactInfoDialog(mContext);
                concatInfoWindow.setOwnerActivity(getActivity());
                concatInfoWindow.show(contact);*/
                Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("contact", contact);
                intent.putExtras(bundle);
                getActivity().startActivity(intent);
                return false;
            }
        });
        mAddFriendView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindowMenu();
            }
        });
        mAddFriendView.setVisibility(View.VISIBLE);
        mToolbar.bringToFront();

    }

    private void showPopupWindowMenu() {
        mPopupWindow.showAsDropDown(mAddFriendView, -20, 5, Gravity.LEFT);
    }

    private void initPopupWindowMenu() {
        View view = View.inflate(mContext, R.layout.toolbar_popwindow_menu, null);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mPopupWindow != null && mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        View addFriends = view.findViewById(R.id.pop_menu_add);
        View createGroupView = view.findViewById(R.id.pop_menu_qunliao);
        addFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                Intent intent = new Intent(mContext, SearchContactActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        });
        createGroupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                Intent intent = new Intent(mContext, SelectGroupMemberActivity.class);
                mContext.startActivity(intent);
            }
        });
    }

    public void initData() {
        List<String> groupTitleList = new ArrayList<>();
        groupTitleList.add("我的好友");
        groupTitleList.add("手机通讯录");
        groupTitleList.add("我的群组");
        if (TextUtils.isEmpty(UserManager.getOrgName())) {
            groupTitleList.add("企业");
        }else {
            groupTitleList.add(UserManager.getOrgName());
        }
        groupTitleList.add("常用联系人");
        //这里只用传最近联系过的联系人就行
        mRecentContactList = ContactManager.getRecentContact();
        if (mAdapter != null) {
            mAdapter.setData(groupTitleList, mRecentContactList);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        //保证在数据更新前添加observer即可
        ContactManager.addContactRefreshListenner(this);
        super.onResume();
    }

    @Override
    public void onPause() {
        ContactManager.removeContactRefreshListenner(this);
        super.onPause();
    }

    /**
     * 在ContactManager中定义的接口回调，任何联系人数据的变化
     * 都会回调到这里重新刷新数据
     */
    @Override
    public void onRefresh() {
        initData();
    }

}
